<template>
    <div class="container">
        <MyHeader @addTodo="addTodo"></MyHeader>
        <MyList :todos="todos"></MyList>
        <MyFooter :todos="todos" @clearAll="clearAll" @checkAll="checkAll"></MyFooter>
    </div>
</template>

<script>

import MyHeader from './components/MyHeader';
import MyFooter from './components/MyFooter';
import MyList from './components/MyList';

export default {
    name: 'App',
    components: {
        MyHeader,
        MyList,
        MyFooter
    },
    data() {
        return {
            todos: JSON.parse(localStorage.getItem('todos')) || []
        }
    },
    methods: {
        addTodo(obj) {
            this.todos.unshift(obj)
        },
        delTodo(id) {
            this.todos = this.todos.filter((todo) => {
                return todo.id != id
            })
        },
        clearAll() {
            this.todos = this.todos.filter((todo) => {
                return !todo.done
            })
        },
        checkAll(value) {
            this.todos.forEach(todo => {
                todo.done = value
            });
        }
    },
    watch: {
        todos: {
            deep: true,
            handler(value) {
                localStorage.setItem('todos', JSON.stringify(value))
            }
        }
    },
    mounted() {
        this.$bus.$on('delTodo',this.delTodo)
    },
    beforeDestroy() {
        this.$bus.$off('delTodo')
    },
}
</script>

<style>
* {
    padding: 0;
    margin: 0 auto;
}

.container {
    width: 800px;
    margin-top: 100px;
    text-align: center;
}
</style>